"""
AI Integration Models
AI功能集成数据模型
"""
import uuid
import json
from django.db import models
from django.contrib.auth import get_user_model
from django.utils import timezone
from django.core.validators import MinValueValidator, MaxValueValidator

User = get_user_model()

class AIGeneratedQuestion(models.Model):
    """AI生成的题目"""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='ai_generated_questions')

    # 题目基本信息
    subject = models.CharField(max_length=50, db_index=True)
    topic = models.CharField(max_length=200, db_index=True)
    difficulty = models.CharField(
        max_length=10,
        choices=[
            ('easy', '简单'),
            ('medium', '中等'),
            ('hard', '困难')
        ],
        db_index=True
    )
    question_type = models.CharField(
        max_length=20,
        choices=[
            ('single_choice', '单选题'),
            ('multiple_choice', '多选题'),
            ('true_false', '判断题'),
            ('short_answer', '简答题'),
            ('essay', '论述题'),
            ('fill_blank', '填空题')
        ]
    )

    # 题目内容
    title = models.CharField(max_length=500)
    content = models.TextField()
    options = models.JSONField(default=list, blank=True)
    correct_answer = models.TextField()
    explanation = models.TextField(blank=True)

    # 题目属性
    estimated_time = models.PositiveIntegerField(default=300, help_text="预估答题时间（秒）")
    score = models.PositiveIntegerField(default=10)

    # AI生成信息
    generation_prompt = models.TextField(blank=True)
    ai_model = models.CharField(max_length=50, default='')
    generation_tokens = models.PositiveIntegerField(default=0)
    quality_score = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        null=True,
        blank=True,
        validators=[MinValueValidator(0), MaxValueValidator(100)]
    )

    # 状态管理
    is_approved = models.BooleanField(default=False)
    approved_by = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='approved_ai_questions'
    )
    approved_at = models.DateTimeField(null=True, blank=True)

    # 使用统计
    usage_count = models.PositiveIntegerField(default=0)
    last_used_at = models.DateTimeField(null=True, blank=True)

    # 时间戳
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'ai_generated_questions'
        verbose_name = 'AI生成题目'
        verbose_name_plural = 'AI生成题目'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['user', 'subject', 'difficulty']),
            models.Index(fields=['question_type', 'is_approved']),
        ]

    def __str__(self):
        return f"{self.subject} - {self.title}"

    def mark_as_used(self):
        """标记题目被使用"""
        self.usage_count += 1
        self.last_used_at = timezone.now()
        self.save(update_fields=['usage_count', 'last_used_at'])

    def approve(self, admin_user):
        """批准题目"""
        self.is_approved = True
        self.approved_by = admin_user
        self.approved_at = timezone.now()
        self.save()

class AIGradingResult(models.Model):
    """AI评分结果"""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='ai_grading_results')

    # 关联信息
    exam_submission_id = models.CharField(max_length=100, null=True, blank=True)
    question_id = models.CharField(max_length=100, null=True, blank=True)

    # 评分信息
    grading_type = models.CharField(
        max_length=20,
        choices=[
            ('essay', '作文评分'),
            ('short_answer', '简答题评分'),
            ('code_review', '代码评分'),
            ('project', '项目评分')
        ]
    )

    # 原始内容
    student_answer = models.TextField()
    reference_answer = models.TextField(blank=True)
    grading_prompt = models.TextField(blank=True)

    # AI评分结果
    ai_score = models.DecimalField(max_digits=5, decimal_places=2)
    max_score = models.DecimalField(max_digits=5, decimal_places=2)
    score_percentage = models.DecimalField(max_digits=5, decimal_places=2)

    # 详细反馈
    strengths = models.JSONField(default=list, help_text="优点列表")
    weaknesses = models.JSONField(default=list, help_text="不足列表")
    detailed_feedback = models.TextField(help_text="详细评语")
    suggestions = models.JSONField(default=list, help_text="改进建议")

    # AI处理信息
    ai_model = models.CharField(max_length=50)
    processing_time = models.DurationField(help_text="AI处理时间")
    tokens_used = models.PositiveIntegerField(default=0)

    # 人工审核
    human_verified = models.BooleanField(default=False)
    human_adjusted_score = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        null=True,
        blank=True
    )
    human_reviewer = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='reviewed_ai_grading'
    )
    human_comments = models.TextField(blank=True)

    # 质量评估
    confidence_score = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        null=True,
        blank=True,
        validators=[MinValueValidator(0), MaxValueValidator(100)]
    )
    accuracy_rating = models.CharField(
        max_length=10,
        choices=[
            ('low', '低'),
            ('medium', '中'),
            ('high', '高')
        ],
        default='medium'
    )

    # 时间戳
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'ai_grading_results'
        verbose_name = 'AI评分结果'
        verbose_name_plural = 'AI评分结果'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['user', 'grading_type']),
        ]

    def __str__(self):
        return f"{self.user.username} - {self.get_grading_type_display()}"

class AIAnalytics(models.Model):
    """AI分析结果"""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='ai_analytics')

    # 分析类型
    analysis_type = models.CharField(
        max_length=30,
        choices=[
            ('learning_progress', '学习进度分析'),
            ('performance_prediction', '成绩预测'),
            ('knowledge_gap', '知识缺口分析'),
            ('study_recommendations', '学习建议'),
            ('difficulty_adaptation', '难度自适应'),
            ('behavior_pattern', '行为模式分析')
        ]
    )

    # 分析数据
    input_data = models.JSONField(help_text="输入的原始数据")
    analysis_result = models.JSONField(help_text="AI分析结果")
    insights = models.TextField(help_text="关键洞察")
    recommendations = models.JSONField(default=list, help_text="建议列表")

    # 分析范围
    subject = models.CharField(max_length=50, blank=True)
    time_period = models.CharField(max_length=20, blank=True)  # 例如: "last_30_days"

    # AI处理信息
    ai_model = models.CharField(max_length=50)
    processing_time = models.DurationField()
    tokens_used = models.PositiveIntegerField(default=0)
    confidence_level = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        null=True,
        blank=True,
        validators=[MinValueValidator(0), MaxValueValidator(100)]
    )

    # 应用状态
    is_applied = models.BooleanField(default=False, help_text="是否已应用建议")
    applied_at = models.DateTimeField(null=True, blank=True)
    effectiveness_rating = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        null=True,
        blank=True,
        validators=[MinValueValidator(0), MaxValueValidator(10)]
    )

    # 时间戳
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'ai_analytics'
        verbose_name = 'AI分析结果'
        verbose_name_plural = 'AI分析结果'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['user', 'analysis_type']),
            models.Index(fields=['subject', 'created_at']),
        ]

    def __str__(self):
        return f"{self.user.username} - {self.get_analysis_type_display()}"

class AIUsageLog(models.Model):
    """AI使用日志"""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='ai_usage_logs')

    # 使用信息
    service_type = models.CharField(
        max_length=30,
        choices=[
            ('question_generation', '题目生成'),
            ('grading_assistant', '评分助手'),
            ('analytics', '智能分析'),
            ('content_moderation', '内容审核'),
            ('adaptive_learning', '自适应学习')
        ]
    )

    # 请求信息
    request_data = models.JSONField(help_text="请求数据")
    response_data = models.JSONField(help_text="响应数据")

    # 性能指标
    response_time = models.DurationField(help_text="响应时间")
    tokens_used = models.PositiveIntegerField(default=0)
    success = models.BooleanField(default=True)
    error_message = models.TextField(blank=True)

    # 质量评估
    user_satisfaction = models.IntegerField(
        null=True,
        blank=True,
        validators=[MinValueValidator(1), MaxValueValidator(5)]
    )
    feedback = models.TextField(blank=True)

    # 成本追踪
    api_cost = models.DecimalField(
        max_digits=10,
        decimal_places=4,
        default=0,
        help_text="API调用成本"
    )

    # 时间戳
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'ai_usage_logs'
        verbose_name = 'AI使用日志'
        verbose_name_plural = 'AI使用日志'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['user', 'service_type', 'created_at']),
            models.Index(fields=['success', 'created_at']),
        ]

    def __str__(self):
        return f"{self.user.username} - {self.get_service_type_display()}"

class AIModelMetrics(models.Model):
    """AI模型性能指标"""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    model_name = models.CharField(max_length=50)
    model_version = models.CharField(max_length=20)

    # 性能指标
    accuracy = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        null=True,
        blank=True,
        validators=[MinValueValidator(0), MaxValueValidator(100)]
    )
    precision = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        null=True,
        blank=True,
        validators=[MinValueValidator(0), MaxValueValidator(100)]
    )
    recall = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        null=True,
        blank=True,
        validators=[MinValueValidator(0), MaxValueValidator(100)]
    )
    f1_score = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        null=True,
        blank=True,
        validators=[MinValueValidator(0), MaxValueValidator(100)]
    )

    # 使用统计
    total_requests = models.PositiveIntegerField(default=0)
    successful_requests = models.PositiveIntegerField(default=0)
    failed_requests = models.PositiveIntegerField(default=0)
    average_response_time = models.DurationField(null=True, blank=True)

    # 质量反馈
    average_user_satisfaction = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        null=True,
        blank=True,
        validators=[MinValueValidator(1), MaxValueValidator(5)]
    )

    # 时间范围
    metrics_date = models.DateField(db_index=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'ai_model_metrics'
        verbose_name = 'AI模型性能指标'
        verbose_name_plural = 'AI模型性能指标'
        ordering = ['-metrics_date']
        unique_together = ['model_name', 'model_version', 'metrics_date']
        indexes = [
            models.Index(fields=['model_name', 'metrics_date']),
        ]

    def __str__(self):
        return f"{self.model_name} - {self.metrics_date}"

    def calculate_success_rate(self):
        """计算成功率"""
        if self.total_requests == 0:
            return 0
        return (self.successful_requests / self.total_requests) * 100